package cc.linker.steplink.crm.merchanth5.controller;

import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.response.GlobalException;
import com.mongodb.util.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/jsapi")
public class JsapiController {

    @Autowired
    private HttpService httpService;

    @Value("${system.scrm.wxpushurl}")
    private String wxpushurl;

    @Autowired
    private RequestFilter requestFilter;

    /**
     * 获取jsapi签名
     * @return
     */
    @PostMapping("/getsign")
    @ResponseBody
    public Map info(@RequestBody Map<String, String> params, HttpServletRequest request) throws IOException, URISyntaxException, GlobalException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String token = wxUser.getToken();
        String action = "getJsapiParams";
        String url = params.get("url");

        Map<String,String> param = new HashMap<>();
        param.put("token",token);
        param.put("action",action);
        param.put("url",url);

        JSONObject jsonObject = (JSONObject)JSONArray.toJSON(param);
        String result = httpService.doPost(wxpushurl, jsonObject.toJSONString());
        Object parse = JSON.parse(result);
        Map ret = (Map) parse;
        if(200 == (Integer) ret.get("errcode")){
            return (Map) ret.get("data");
        }
        throw GlobalException.build(ret.get("msg").toString());
    }
}
